
#include "stdafx.h"

#include "pf_pattern.h"

#include "pf_system.h"
#include "pf_fileio.h"
#include "pf_layer.h"


/**
 * Constructor.
 *
 * @param fileName File name of a DXF file defining the pattern
 */
PF_Pattern::PF_Pattern(const QString& fileName)
        : PF_Container(NULL) {

    PF_DEBUG->print("PF_Pattern::PF_Pattern() ");

	this->fileName = fileName;
	loaded = false;
}



/**
 * Constructor.
 *
 * @param fileName File name of a PAT file which defines this 
 *         pattern among others.
 * @param name Pattern name.
 *
 */
/*PF_Pattern::PF_Pattern(const QString& fileName, const QString& name)
        : PF_EntityContainer(NULL) {
	this->fileName = fileName;
	this->name = name;
	loaded = false;
}*/



PF_Pattern::~PF_Pattern() {}


/**
 * Loads the given pattern file into this pattern.
 * Entities other than lines are ignored.
 *
 * @param filename File name of the pattern file (without path and 
 * extension or full path.
 */
bool PF_Pattern::loadPattern() {
    if (loaded) {
        return true;
    }

	PF_DEBUG->print("PF_Pattern::loadPattern");

    QString path;

    // Search for the appropriate pattern if we have only the name of the pattern:
    if (!fileName.toLower().contains(".dxf")) {
        QStringList patterns = PF_SYSTEM->getPatternList();
        QFileInfo file;
        for (QStringList::Iterator it = patterns.begin();
                it!=patterns.end();
                it++) {

            if (QFileInfo(*it).baseName().toLower()==fileName.toLower()) {
                path = *it;
                                PF_DEBUG->print("Pattern found: %s", path.toLatin1().data());
                break;
            }
        }
    }

    // We have the full path of the pattern:
    else {
        path = fileName;
    }

    // No pattern paths found:
    if (path.isEmpty()) {
        PF_DEBUG->print("No pattern \"%s\"available.", fileName.toLatin1().data());
        return false;
    }

	PF_Graphic* gr = new PF_Graphic();

	// TODO: Find out why the new dxf filter doesn't work for patterns:
	PF_FILEIO->fileImport(*gr, path, LX_Define::FormatDXF1);

	for (PF_Entity* e=gr->firstEntity(); e!=NULL; e=gr->nextEntity()) {
		if (e->rtti()==LX_Define::EntityLine || e->rtti()==LX_Define::EntityArc) {
			PF_Layer* l = e->getLayer();
			PF_Entity* cl = e->clone();
			cl->reparent(this);
			if (l!=NULL) {
				cl->setLayer(l->getName());
			}
			addEntity(cl);
		}
	}
	delete gr;

    loaded = true;
	PF_DEBUG->print("PF_Pattern::loadPattern: OK");

	return true;
}

